package com.doubleboy.flashlight.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.view.animation.OvershootInterpolator;
import android.widget.FrameLayout;

import com.doubleboy.flashlight.R;
import com.doubleboy.flashlight.lang.L;

/**
 * 新版开关，采用动画和手势结合的机制，适用于android4.0
 * Created by xzz on 14-3-16.
 */
public class SlideButton extends FrameLayout {

	//size & position
	int weightHeight;
	int btnHeight;
    int missHeight = 40;
    int endPostion;
    //
	private OnTouchListener onTouch;
	private OnGestureListener onGesture;
	private GestureDetector detector;
	private Context context;
	//slide button
	private View button;
	private View light;
    Interpolator sDecelerator = new DecelerateInterpolator();
    Interpolator sAccelerator = new AccelerateInterpolator();
    Interpolator sOvershooter = new OvershootInterpolator(2f);

    private OnChangedListener changListener;
    private boolean isOpen = false;

    public SlideButton(Context context, AttributeSet attrs) {
        super(context,attrs);
		this.context = context;
		LayoutInflater.from(context).inflate(R.layout.slide_button, this);
		button = findViewById(R.id.switch_button);
		light = findViewById(R.id.bg_light);
		initListener();
	}

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        if (weightHeight == 0) {
            weightHeight = getHeight();
            btnHeight = button.getHeight();
            L.i("weightHeight:%S,%S", weightHeight, btnHeight);
            endPostion = weightHeight - btnHeight - missHeight;
            button.setTranslationY(isOpen ? 0 : endPostion);
            light.setAlpha(isOpen ? 1 : 0);
        }
    }

    /**
     * 初始化状态（不带动画）
     *
     * @param isOpen
     *            　目的状态
     */
    public void initStatu(boolean isOpen) {
        this.isOpen = isOpen;
        if (!isOpen) {
            L.d("关de");
            button.setTranslationY(endPostion);
            light.setAlpha(0);
        } else {
            L.d("开de");
            button.setTranslationY(0);
            light.setAlpha(0.8f);
        }
    }

    public void toggleStatu(boolean isOpen) {
        this.isOpen = isOpen;
        changeAnimator();
    }

    //用于识别手势漏掉的状态
    boolean eventFinished = true;

    /**
     * 初始化手势识别
     */
    private void initListener() {

        onGesture = new GestureDetector.SimpleOnGestureListener() {

            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                L.i(null);
                return false;
            }

            ;

			@Override
			public boolean onDown(MotionEvent e) {
				L.i(null);
				return false;
			}

			@Override
			public void onShowPress(MotionEvent e) {
				L.i(null);
			}

			@Override
			public boolean onSingleTapUp(MotionEvent e) {
                changeAnimator();
                eventFinished = true;
                return true;
			}

			@Override
			public boolean onScroll(MotionEvent e1, MotionEvent e2,
					float distanceX, float distanceY) {
				float oldPos = button.getTranslationY();
				float newPos = oldPos - distanceY;
                if (newPos > 0 && newPos < endPostion) {
                    button.setTranslationY(newPos);
                    // invalidate();
                }
                eventFinished = false;
                return false;
            }

			@Override
			public void onLongPress(MotionEvent e) {
                L.i("long");
            }

            @Override
            public boolean onFling(MotionEvent e1, MotionEvent e2,
                                   float velocityX, float velocityY) {
                L.i("velocityX: %S,velocityY: %S", velocityX, velocityY);
                changeAnimator(50, 70);
                eventFinished = true;
                return false;
            }
        };

        detector = new GestureDetector(context, onGesture);

        onTouch = new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                detector.onTouchEvent(event);

                if (!eventFinished && event.getAction() == MotionEvent.ACTION_UP) {
                    changeAnimator();
                }
                return true;
            }
        };

        this.setOnTouchListener(onTouch);
    }

    private void changeAnimator() {
        changeAnimator(150, 200);
    }

    private void changeAnimator(int btnTime, int lightTime) {
        if (isOpen) {
            L.d("关 动画");
            button.animate().translationYBy(0).translationY(endPostion).setDuration(btnTime).setInterpolator(sAccelerator).start();
            light.animate().alphaBy(0.8f).alpha(0).setDuration(lightTime).setInterpolator(sDecelerator).start();
        } else {
            L.d("开 动画");
            button.animate().translationYBy(endPostion).translationY(0).setDuration(btnTime).setInterpolator(sAccelerator).start();
            light.animate().alphaBy(0).alpha(0.8f).setDuration(lightTime).setInterpolator(sDecelerator).start();
        }
        isOpen = !isOpen;
        performChange();
    }

    public void performChange() {
        changListener.OnChanged(isOpen);
    }

    public void SetOnChangedListener(OnChangedListener changListener) {
        this.changListener = changListener;
    }

    // 声明监听类
    public interface OnChangedListener {
        abstract void OnChanged(boolean checkStatu);
    }

}
